extends NodeState


var ball: Ball:
	get:
		return state_matchine.root as Ball


var shot_power: float = 0.0
var max_shot_power: float = 1.0
# 重力曲线时间，即曲线x轴
var gravity_curve_time: float
# 最大的重力曲线时间，即曲线x轴的最大值，不应该超过1.0
var max_gravity_curve_time: float


func _on_process(delta : float) -> void:
	process_animation()
	process_shot(delta)
	process_gravity(delta)

	if ball.height < GlobalConstants.TINY:
		transition_state(Ball.STATE_FREEFORM)
		return


func _on_enter(data: NodeStateData) -> void:
	shot_power = 0.0
	max_shot_power = 1.0
	gravity_curve_time = 0.0
	max_gravity_curve_time = 1.0

	ball.height = data.ball_height
	ball.height_velocity = 0.0

	if data is BallShotData:
		shot_power = data.shot_power
		max_shot_power = data.max_shot_power
		max_gravity_curve_time = remap(shot_power, 0.0, max_shot_power, 0.0, 1.0)



func _on_exit() -> void:
	ball.ball_sprite.scale = Vector2.ONE



func process_shot(delta : float):
	ball.move_and_bounce(delta)
	ball.velocity = ball.velocity.move_toward(Vector2.ZERO, ball.friction_air * delta)



func process_gravity(delta : float):
	ball.ball_sprite.position.y = -ball.height

	if ball.height > 0.0:
		ball.height_velocity -= gravity_curve(delta) * delta
		ball.height += ball.height_velocity
	if ball.height < 0.0:
		ball.height = 0.0


# 重力曲线受到射门力量影响
func gravity_curve(delta : float) -> float:
	gravity_curve_time = clampf(gravity_curve_time + delta, 0.0, max_gravity_curve_time)
	var bonus := ease(gravity_curve_time, ball.shot_gravity_curve)
	return GlobalConstants.BALL_GRAVITY * bonus




func process_animation():
	if ball.velocity.x > GlobalConstants.TINY:
		ball.animation_player.play(Ball.ANIMATION_ROLL)
	elif ball.velocity.x < GlobalConstants.TINY_NEGATIVE:
		ball.animation_player.play(Ball.ANIMATION_ROLL_BACK)

	ball.ball_sprite.scale.y = ball.shot_scale
